package com.swan.models;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.swan.exceptions.CustomerException;
import com.swan.utils.EncryptUtil;

public class LoginDao {
    public int login(String loginId, String password) {
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select * from login where login_id = ? and password = ?", loginId, EncryptUtil.MD5(password));
            if (rs.next())
                return rs.getInt("user_id");
            else
                throw new CustomerException("Login id or password invalid.");
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
    }

    public boolean changePassword(String name, String oldPassword, String newPassword) {
        try (DBUtil db = new DBUtil()) {
            return db.updateWithoutGeneratedKey("update login set password = ? where login_id = ? and password = ?", EncryptUtil.MD5(newPassword), name, EncryptUtil.MD5(oldPassword)) == 1;
        }
    }
}
